package com.wk.hooker.hooks;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Message;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
/**
 * Created by wuchu on 16/4/10.
 */
public class HookThread extends Thread {


    private static HookThread hookThread;


    private int sleeptime = 30*1000;


    private android.os.Handler handler ;

    private Context context;


    private Object lock = new Object();

    private  HookThread(){

    }

    public void setSleeptime(int sleeptime) {
        this.sleeptime = sleeptime;
    }

    public void setHandler(android.os.Handler handler) {
        this.handler = handler;
    }

    public void setContext(Context context) {
        this.context = context;
    }

    public static HookThread getIntance(){

        if(hookThread==null){

            hookThread = new HookThread();
        }
        return  hookThread;
    }

    private long alltime =0;

    private boolean isrung = true;

    @Override
    public void run() {
        super.run();
        while (isrung){
            try {
                //启动获取掉线的连接数据
                Thread.sleep(sleeptime);
                sleeptime =30*1000;
                getWeinLoginState();

            } catch (InterruptedException e) {
                e.printStackTrace();
            }catch (Exception e){

            }

        }
        hookThread = null;

    }

    private  void getWeinLoginState(){

        String results =sendGet("http://t.caisiapp.com/onlines", System.currentTimeMillis()+"");
        //判断是否有掉线
        SharedPreferences pref = context.getSharedPreferences("weixinok", Context.MODE_WORLD_READABLE);
        Gson gson = new Gson();
        int flag = 0;
        try {
            ArrayList<WeiXinBean> weixinlist = gson.fromJson(results, new TypeToken<ArrayList<WeiXinBean>>(){}.getType());
            String nickname=pref.getString("WeiXinNumber",null);
            if(nickname==null){
                return;
            }

            for(WeiXinBean weixinbean:weixinlist){
                if(nickname.equals(weixinbean.getNickName())){
                    flag=1;
                }
            }
        }catch (Exception e){
            flag = 2;
        }
        //先获取掉线的数据

       switch (flag){
           case 0://掉线获取获取去获取扫描的二维码
               //启动微信去扫描
               results =sendGet("http://t.caisiapp.com/add-bot-auto", System.currentTimeMillis()+"");

               try {
                   JSONObject jsonObject = new JSONObject(results);
                   SharedPreferences.Editor edit = pref.edit();
                   edit.putString("QR",""+jsonObject.getString("qr"));
                   edit.putInt("login_state",0);
                   edit.commit();
                   if(alltime==0){
                       Message message = handler.obtainMessage(0);
                       message.what = 0;
                       handler.sendMessage(message);
                   }
                   alltime=alltime+30*1000;
                   if(alltime>=120*1000){
                       alltime=0;
                   }
               } catch (JSONException e) {
                   e.printStackTrace();
               }

               break;
           case 1:
               SharedPreferences.Editor edit = pref.edit();
               edit.putInt("login_state",2);
               edit.commit();
               Message message = handler.obtainMessage(1);
               message.what = 1;
               handler.sendMessage(message);
               break;
           case 3:
               Message message2 = handler.obtainMessage(1);
               message2.what = 3;
               handler.sendMessage(message2);
               break;
       }
    }


    private String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        InputStream inputStream =null;
        HttpURLConnection httpUrlConnection =null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            httpUrlConnection = (HttpURLConnection) connection;
            httpUrlConnection.setDefaultUseCaches(false);
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.setConnectTimeout(1000*60);
            connection.setReadTimeout(1000*60);
            // 建立实际的连接

            connection.connect();

            // 定义 BufferedReader输入流来读取URL的响应
            inputStream = connection.getInputStream();
            in = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }

            httpUrlConnection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
            httpUrlConnection.disconnect();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                    inputStream.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }


    public void stopHookService(){
        isrung = false;
        this.interrupt();
        hookThread=null;
    }

    public static  boolean isKill(){

        if(hookThread==null){

        }

        return  true;

    }


    public  void startHookService(){
        isrung = true;
    }

}
